package org.andy.queue;

/**
 * 数组实现队列<br>
 *
 * @author andy
 * @version V1.0
 * @date 18/3/8 下午5:02
 */
public class ArrayBlockQueue<E> implements Queue<E> {

    private Object[] objects;
    private int size;
    private int maxSize;

    /**
     * 构造函数
     *
     * @param maxSize  初始化大小
     */
    public ArrayBlockQueue(int maxSize) {
        if (maxSize <= 0){
            throw new IllegalArgumentException();
        }
        this.objects = new Object[maxSize];
        this.maxSize = maxSize;
    }

    @Override
    public synchronized void put(E e) {
        if (size == objects.length){
            throw new IllegalArgumentException();
        }
        objects[size] = e;
        size++;
    }

    @Override
    public synchronized E pop() {
        if (size == 0){
            return null;
        }
        // 头部数据
        E e = (E) objects[0];
        // 移除头部 数据需要重新转换位置
        for (int i = 0; i< size -1; i++){
            objects[i] = objects[i + 1];
        }
        objects[size -1] = null;
        size--;
        return e;
    }

    public synchronized int size(){
        return size;
    }

    /**
     * 判断是否队满
     */
    public synchronized boolean isFull(){
        return size == maxSize;
    }

}
